<template>
  <div class="RepertoryInquire">
    <a-card>
      <a-form :form="form">
        <a-row :gutter="30">
          <a-col :span="8">
            <a-form-item label="网点名称" :label-col="{ span: 6 }" :wrapper-col="{ span: 16,offset:1}">
              <a-select
                v-decorator="[
          'branchName',
          {rules: [{ required: true, message: '请选择网点名称!' }]}
        ]"
                placeholder="全部"
              >
                <a-select-option :value="-1">全部</a-select-option>
                <a-select-option
                  v-for="item in branchInfo"
                  :key="item.branchesId"
                  :value="item.branchesId"
                >{{item.branchName}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="点位名称" :label-col="{ span: 6}" :wrapper-col="{ span: 16, offset: 1}">
              <a-input
                placeholder="请输入"
                v-decorator="[
          'pointName',
          {rules: [{ required: true, message: '请输入点位名称!' }]}
        ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="设备编号" :label-col="{ span: 6}" :wrapper-col="{ span: 16, offset: 1}">
              <a-input
                placeholder="请输入"
                v-decorator="[
          'facilityNumber',
          {rules: [{ required: true, message: '请输入设备编号!' }]}
        ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="30">
          <a-col :span="8">
            <a-form-item label="库存状态" :label-col="{ span: 6 }" :wrapper-col="{ span: 16,offset:1}">
              <a-select
                v-decorator="[
          'repertorystate',
          {rules: [{ required: true, message: '请选择库存状态!' }]}
        ]"
                placeholder="全部"
              >
                <a-select-option value="1">全部</a-select-option>
                <a-select-option value="2">正常</a-select-option>
                <a-select-option value="3">告警</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="是否有异常" :label-col="{ span: 6 }" :wrapper-col="{ span: 16,offset:1}">
              <a-select
                v-decorator="[
          'isAbnormal',
          {rules: [{ required: true, message: '请选择是否有异常!' }]}
        ]"
                placeholder="全部"
              >
                <a-select-option :value="-1">全部</a-select-option>
                <a-select-option :value="0">有</a-select-option>
                <a-select-option :value="1">无</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="7" :style="{ textAlign: 'right' }">
            <a-button type="primary" @click="search">查询</a-button>
            <a-button type="dashed" @click="listExport">导出</a-button>
            <a-button htmlType="reset">重置</a-button>
          </a-col>
        </a-row>
        <a-row :gutter="30">
          <a-col :span="24">
            <p>
              报警阈值设置：当“库存/标准库存”小余
              <a-input-number v-model="thresholdValue" @blur="setWarning"/>%时，进行报警提示。
            </p>
          </a-col>
          <a-col>
            <p>盘存说明：盘库功能主要作用于设备库存的从新盘点，每天每台设备只有一次使用机会。</p>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card style="margin-top:2%;">
      <a-table
        :columns="columns"
        :dataSource="data"
        :pagination="pagination"
        @change="handleTableChange"
        :rowKey="record => record.devCode"
        :bordered="true"
      >
        <template slot="isAbnormal" slot-scope="text,record">
          <span
            :class="record.isHealthy==0?'examine':''"
            @click="record.isHealthy==0?examineModal(text,record):''"
          >{{record.isHealthy==0?"查看异常":"无"}}</span>
        </template>
        <template slot="inventoryStatus" slot-scope="text,record">
          <span>{{record.stockStatus==0?"正常":"告警"}}</span>
        </template>
        <template slot="operation" slot-scope="text,record">
          <span class="inventory" @click="inventory(record,$event)">盘存</span>

          <span class="details" @click="detailsModal(text,record)">详情</span>
        </template>
      </a-table>
    </a-card>
    <a-modal
      title="查看异常情况"
      :visible="examineVisible"
      @ok="examineOk"
      @cancel="examineCancel"
      :width="1000"
      okText="编辑商品模板"
    >
      <div class="popForm">
        <ul>
          <li v-for="(item,index) in devicePicList" :key="index">第{{item.floor}}层</li>
        </ul>
        <p>盘存图片：</p>
        <ul>
          <li v-for="(item,index) in devicePicList" :key="index">
            <img :src="item.picUrl" alt="图片加载不成功">
          </li>
        </ul>
        <p>识别结果：</p>
        <p v-for="(item,index) in resultList" :key="index">{{resultList[index]}}</p>
        <hr>
        <p>异常内容：</p>
        <p>{{errorMsg}}</p>
        <hr>
        <p>模板商品：</p>
        <p>{{templateGoods}}</p>
      </div>
    </a-modal>
    <a-modal
      :title="detailsTitle"
      :visible="detailsVisible"
      @ok="detailsOk"
      @cancel="detailsCancel"
      :footer="null"
      :width="1000"
    >
      <a-form :form="form">
        <a-row :gutter="30">
          <a-col :span="8">
            <a-form-item
              v-show="false"
              label="开始时间"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 15,offset:1 }"
            >
              <a-range-picker
                style="width: 100%"
                v-decorator="['startTime',
          {rules: [{ required: true, message: '请选择开始时间!' }]}]"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-button type="primary">查询</a-button>
            <a-button type="dashed" @click="exportDetail">导出</a-button>
            <a-button htmlType="reset">重置</a-button>
          </a-col>
          <a-col :span="8" style="text-align:right">
            <a-button type="primary" @click="setInventory" v-show="isSetInventory">设置标准库存</a-button>
            <a-button
              @click="setStandard()"
              v-show="isFinish"
              style="background:rgb(0,204,102);color:white"
            >完成标准库存设置</a-button>
            <a-button
              @click="setCancel"
              v-show="isCancel"
              style="background:rgb(245,34,45);color:white"
            >取消</a-button>
          </a-col>
        </a-row>
      </a-form>
      <a-row :gutter="30">
        <a-col :span="24">
          <p>
            剩余总库存：
            <span>{{stockTotal}}</span>
          </p>
        </a-col>
      </a-row>
      <a-table
        :columns="columnsPop"
        :dataSource="dataPop"
        @change="handleTablePop"
        :rowKey="record => record.deviceGoodsId"
        :bordered="true"
        :pagination="false"
      >
        <template slot="normRepertory" slot-scope="text,record">
          <div key="normRepertory">
            <span>{{record.standardStock}}</span>
            <a-input
              v-show="isInput"
              :value="text"
              @change="e => inputNumberChange(e.target.value,record.goodsId)"
              style="width:35%;margin-left:5%"
            />
          </div>
        </template>
      </a-table>
      <p style="margin-top:1%">库存更新日志</p>
      <ul v-for="item in logList" :key="item.index">
        <li>
          <span>{{item.createTime}}</span>
          <span>{{item.operationTypeName}}</span>
          <span>{{item.description}}</span>
        </li>
      </ul>
    </a-modal>
  </div>
</template>

<script>
const columns = [
  {
    title: "点位名称",
    dataIndex: "posName",
    scopedSlots: { customRender: "pointName" },
    align: "center"
  },
  {
    title: "设备编号",
    dataIndex: "devCode",
    scopedSlots: { customRender: "facilityNumber" },
    align: "center"
  },
  {
    title: "点位地址",
    dataIndex: "posAddress",
    scopedSlots: { customRender: "pointSite" },
    align: "center"
  },
  {
    title: "是否有异常",
    dataIndex: "isHealthy",
    scopedSlots: { customRender: "isAbnormal" },
    align: "center"
  },
  {
    title: "剩余库存",
    dataIndex: "stock",
    scopedSlots: { customRender: "residueInventory" },
    sorter: true,
    align: "center"
  },
  {
    title: "标准库存",
    dataIndex: "standardStock",
    scopedSlots: { customRender: "normInventory" },
    sorter: true,
    align: "center"
  },
  {
    title: "库存阈值",
    dataIndex: "stockRate",
    scopedSlots: { customRender: "inventoryThreshold" },
    align: "center"
  },
  {
    title: "库存状态",
    dataIndex: "stockStatus",
    scopedSlots: { customRender: "inventoryStatus" },
    align: "center"
  },
  {
    title: "操作",
    dataIndex: "operation",
    scopedSlots: { customRender: "operation" },
    align: "center"
  }
];
// 弹窗表格列设置
const columnsPop = [
  {
    title: "商品名称",
    dataIndex: "goodsName",
    scopedSlots: { customRender: "goodsName" },
    align: "center"
  },
  {
    title: "占用列",
    dataIndex: "occupancyColumn",
    scopedSlots: { customRender: "takeColumn" },
    align: "center"
  },
  {
    title: "货道可放置商品数",
    dataIndex: "placementNumber",
    scopedSlots: { customRender: "placeNumber" },
    align: "center"
  },
  {
    title: "已售",
    dataIndex: "sales",
    scopedSlots: { customRender: "soldOut" },
    align: "center"
  },
  {
    title: "库存",
    dataIndex: "stock",
    scopedSlots: { customRender: "repertory" },
    align: "center"
  },
  {
    title: "实际上货",
    dataIndex: "reality",
    scopedSlots: { customRender: "realityExhibitGoods" },
    align: "center"
  },
  {
    title: "标准库存",
    dataIndex: "standardStock",
    scopedSlots: { customRender: "normRepertory" },
    align: "center"
  },
  {
    title: "待补货",
    dataIndex: "replenishNumber",
    scopedSlots: { customRender: "replenishment" },
    align: "center"
  }
];
// 弹窗表格数据
const dataPop = [
  {
    key: "1",
    pointName: "John Brown",
    facilityNumber: 32,
    pointSite: "New York No. 1 Lake Park",
    isAbnormal: ["nice", "developer"],
    residueInventory: "",
    normInventory: "",
    inventoryThreshold: "",
    inventoryStatus: ""
  },
  {
    key: "2",
    pointName: "Jim Green",
    facilityNumber: 42,
    pointSite: "London No. 1 Lake Park",
    isAbnormal: ["loser"],
    residueInventory: "",
    normInventory: "",
    inventoryThreshold: "",
    inventoryStatus: ""
  },
  {
    key: "3",
    pointName: "Joe Black",
    facilityNumber: 32,
    pointSite: "Sidney No. 1 Lake Park",
    isAbnormal: ["cool", "teacher"],
    residueInventory: "",
    normInventory: "",
    residueInventory: "",
    inventoryStatus: ""
  }
];
export default {
  name: "RepertoryInquire",
  data() {
    this.oldData = [];
    return {
      form: this.$form.createForm(this),
      thresholdValue: "30", //阈值
      columns,
      data: [],
      pagination: {
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ["2", "4", "8", "10", "12"],
        showTotal: (total, range) => {
          return `${range[0]}-${range[1]} 共${total}条`;
        },
        pageSize: 5,
        defaultCurrent: 1,
        current: 1,
        total: 500
      },
      columnsPop,
      dataPop: [],
      stockTotal: "",
      examineVisible: false,
      detailsVisible: false,
      isSetInventory: true,
      isInput: false,
      isFinish: false,
      isCancel: false,
      normValue: "",
      detailsTitle: "",
      logList: [],
      branchInfo: [],
      deviceInfo: [],
      devicePicList: [],
      resultList: [],
      errorMsg: "",
      templateGoods: "",
      goodsTemplateId: Number
    };
  },
  watch: {},
  computed: {},
  methods: {
    inputNumberChange(value, key) {
      const newData = [...this.dataPop];
      const target = newData.filter(item => key === item.goodsId)[0];
      if (target) {
        target["standardStock"] = value;
        this.dataPop = newData;
      }
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      pager.pageSize = pagination.pageSize;
      pager.total = pagination.total;
      this.pagination = pager;
      this.search();
    },
    // 弹窗表格方法
    handleTablePop(pagination, filters, sorter) {
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      pager.pageSize = pagination.pageSize;
      pager.total = pagination.total;
      this.pagination = pager;
      // this.search();
    },
    // 查看异常弹窗
    examineModal(text, record) {
      this.examineVisible = true;
      this.errorInfo(record.devCode, record.deviceAgentId);
    },
    examineOk(e) {
      this.examineVisible = false;
      this.$store.commit("goodsTemplateId", this.goodsTemplateId);
      this.$router.push({
        path: "/home/goodsadmin/templateadmin/templateedit"
      });
    },
    examineCancel(e) {
      this.examineVisible = false;
    },
    // 详情弹窗
    detailsModal(text, record) {
      this.detailsVisible = true;
      this.listDetail(record);
      this.record = record;
      this.detailsTitle =
        "库存详情" + "-" + record.devCode + "-" + record.posName;
    },
    detailsOk(e) {
      this.detailsVisible = false;
    },
    detailsCancel(e) {
      this.detailsVisible = false;
    },
    // 设置标准库存
    setInventory() {
      this.isInput = true;
      this.isSetInventory = false;
      this.isFinish = true;
      this.isCancel = true;
    },

    // 取消设置标准库存
    setCancel() {
      this.isInput = false;
      this.isFinish = false;
      this.isCancel = false;
      this.isSetInventory = true;
    },

    // 网点下拉框列表
    branchList() {
      this.axios
        .post(this.baseUrl + "/stock/branchList", {
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          // console.log(response);
          this.branchInfo = response.data.data;
        });
    },

    // 代理商库存搜索
    search() {
      var values = this.form.getFieldsValue();
      this.axios
        .post(this.baseUrl + "/stock/search", {
          loginToken: this.$store.state.loginToken,
          branchesId: values.branchName,
          devCode: values.facilityNumber,
          isHealthy: values.isAbnormal,
          posName: values.pointName,
          sortType: 1,
          stockStatus: values.repertorystate,
          pageNum: this.pagination.current,
          pageSize: this.pagination.pageSize
        })
        .then(response => {
          // console.log(response);
          this.data = response.data.data.list;
          this.pagination.total = response.data.data.total;
          this.pagination.pageSize = response.data.data.pageSize;
          this.pagination.current = response.data.data.pageNum;
        })
        .catch(error => {
          console.log(error);
        });
    },

    // 查看异常
    errorInfo(devCode, deviceAgentId) {
      this.axios
        .post(this.baseUrl + "/stock/errorInfo", {
          loginToken: this.$store.state.loginToken,
          devCode: devCode,
          deviceAgentId: deviceAgentId
        })
        .then(response => {
          console.log(response);
          this.devicePicList = response.data.data.devicePicList;
          this.resultList = response.data.data.resultList;
          this.errorMsg = response.data.data.errorMsg;
          this.templateGoods = response.data.data.templateGoods;
          this.goodsTemplateId = response.data.data.goodsTemplateId;
        });
    },

    // 获取报警阈值
    getWarning() {
      this.axios
        .post(this.baseUrl + "/stock/getWarning", {
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          // console.log(response);
          this.thresholdValue = response.data.data.value;
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 报警阈值设置
    setWarning() {
      this.axios
        .post(this.baseUrl + "/stock/setWarning", {
          loginToken: this.$store.state.loginToken,
          value: this.thresholdValue
        })
        .then(response => {
          console.log(response);
          if (response.data.code == 0) {
            // this.search();
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 盘存
    inventory(record, e) {
      this.axios
        .post(this.baseUrl + "/stock/inventory", {
          loginToken: this.$store.state.loginToken,
          devCode: record.devCode,
          deviceAgentId: record.deviceAgentId
        })
        .then(response => {
          // console.log(response);
          if (response.data.code == 0) {
            e.target.style.color = "rgb(179,179,179)";
            this.$message.success("盘存成功");
          }
          if (response.data.code !== 0) {
            this.$message.error(response.data.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 库存详情
    listDetail(record) {
      this.axios
        .post(this.baseUrl + "/stock/detail", {
          loginToken: this.$store.state.loginToken,
          deviceAgentId: record.deviceAgentId,
          devCode: record.devCode
        })
        .then(response => {
          // console.log(response);
          this.dataPop = response.data.data.detailList;
          this.oldData = response.data.data.detailList;
          this.logList = response.data.data.logList;
          this.stockTotal = response.data.data.stockTotal;
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 代理商库存详情导出
    exportDetail() {
      this.axios
        .post(
          this.baseUrl + "/stock/exportDetail",
          {
            loginToken: this.$store.state.loginToken,
            deviceAgentId: this.record.deviceAgentId,
            devCode: this.record.devCode
          },
          { responseType: "arraybuffer" }
        )
        .then(response => {
          console.log(response);
          if (response.status == "200") {
            const aLink = document.createEflement("a");
            let blob = new Blob([response.data], {
              type: "application/vnd.ms-excel"
            });
            aLink.href = URL.createObjectURL(blob);
            aLink.download = "代理商库存详情表";
            aLink.click();
            document.body.appendChild(aLink);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 设置标准库存
    setStandard() {
      this.isInput = false;
      this.isFinish = false;
      this.isCancel = false;
      this.isSetInventory = true;
      var values = this.form.getFieldsValue();
      this.axios
        .post(this.baseUrl + "/stock/setStandard", {
          loginToken: this.$store.state.loginToken,
          devCode: this.record.devCode,
          deviceAgentId: this.record.deviceAgentId,
          standardStockList: this.dataPop
        })
        .then(response => {
          // console.log(response);
          this.$message.success("修改成功");
          this.listDetail();
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 代理商库存导出
    listExport() {
      var values = this.form.getFieldsValue();
      this.axios
        .post(
          this.baseUrl + "/stock/export",
          {
            loginToken: this.$store.state.loginToken,
            branchesId: values.branchName,
            devCode: values.facilityNumber,
            isHealthy: values.isAbnormal,
            posName: values.pointName,
            sortType: 1,
            stockStatus: values.repertorystate
          },
          { responseType: "arraybuffer" }
        )
        .then(response => {
          console.log(response);
          if (response.status == "200") {
            const aLink = document.createElement("a");
            let blob = new Blob([response.data], {
              type: "application/vnd.ms-excel"
            });
            aLink.href = URL.createObjectURL(blob);
            aLink.download = "库存查询表";
            aLink.click();
            document.body.appendChild(aLink);
          }
        })
        .catch(error => {
          console.log(error);
        });
    }
  },
  created() {
    this.branchList();
    this.search();
    this.getWarning();
  },
  mounted() {}
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.RepertoryInquire {
  width: 100%;
}
.ant-btn-primary,
.ant-btn-dashed {
  margin-right: 10px;
}
.examine,
.inventory,
.details {
  color: rgb(98, 144, 255);
  cursor: pointer;
}
.popForm {
  padding: 0 1%;
}
.popForm ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.popForm img {
  width: 100%;
}
.popForm p {
  margin: 1% 0;
}
ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
ul li {
  margin: 10px 0;
}
</style>
